package com.ayq.activiti.manager.listener;

import com.ayq.activiti.common.util.ConstantPool;
import com.ayq.activiti.manager.config.SpringUtil;
import com.ayq.activiti.manager.domain.examinedistribution.entity.ActivitiExamineDistribution;
import com.ayq.activiti.manager.domain.examinedistribution.repository.ActivitiExamineDistributionMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Component
public class ApplyTaskListener implements TaskListener {

    private static final long serialVersionUID = -6989469817476577413L;

    private ActivitiExamineDistributionMapper activitiExamineDistributionMapper;

    @Override
    @Transactional
    public void notify(DelegateTask delegateTask) {
        String taskKey = delegateTask.getTaskDefinitionKey();
        Map<String,Object> variables = delegateTask.getVariables();
        Long amId = (Long)variables.get(ConstantPool.ACTIVITI_MANAGER_ID);
        QueryWrapper<ActivitiExamineDistribution> wrapper = new QueryWrapper<ActivitiExamineDistribution>();
        wrapper.eq(ConstantPool.TASK_KEY,taskKey).eq(ConstantPool.ACTIVITI_MANAGER_ID,amId);
        ActivitiExamineDistribution activitiExamineDistribution = activitiExamineDistributionMapper.selectOne(wrapper);
        String examineIds = activitiExamineDistribution.getExamineIds();
        String[] split = examineIds.split(",");
        //如未进行配置则无法发出流程
        if(activitiExamineDistribution == null || split.length == 0){
            throw new RuntimeException();
        }else {
            for (String userId : split) {
                delegateTask.addCandidateUser(userId);
            }
        }
    }

    public ApplyTaskListener() {
        this.activitiExamineDistributionMapper = SpringUtil.getApplicationContext().getBean(ActivitiExamineDistributionMapper.class);
    }
}
